<template>
  <el-dialog :visible.sync="showPointDialog" :before-close="check" title="优惠策略" width="70%">
    <div class="app-container">
      <div class="app-head">
        <el-form>
          <el-row type="flex" justify="start">
            <el-col :span="14">
              <el-form-item label="优惠策略名称" label-width="100px">
                <el-input ref="vipHeight" v-model="name" style="width:90%" size="mini" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="策略触发条件" label-width="100px">
                <el-select v-model="triggeringConditions" style="width:90%" size="mini" placeholder="请选择">
                  <el-option value="" label="全部" />
                  <el-option
                    v-for="item in triggeringConditionsArr"
                    :key="item.typeId"
                    :value="item.typeId"
                    :label="item.typeName"
                    :disabled="item.status"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="2" class="flexd">
              <el-button
                size="mini"
                round
                type="primary"
                icon="el-icon-search"
                @click="loadList"
              >查询</el-button>
            </el-col>
            <!-- <el-col :span="1" class="absolute main-button">
              <el-button
                size="mini"
                style="height:35px"
                type="primary"
                icon="el-icon-refresh"
                @click="reset"
              >
                重置
              </el-button>
            </el-col> -->
          </el-row>
          <el-row>
            <el-col :span="14">
              <el-form-item label="开始策略时间" label-width="100px">
                <el-date-picker
                  v-model="startDiscount"
                  :picker-options="pickerOptions1"
                  :editable="false"
                  :style="tiemLen"
                  type="datetime"
                  size="mini"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss   "
                  placeholder="选择开始时间"
                  @change="checkStartTime"
                />
                至
                <el-date-picker
                  v-model="startEndDiscount"
                  :picker-options="pickerOptions2"
                  :editable="false"
                  :style="tiemLen"
                  type="datetime"
                  size="mini"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss   "
                  placeholder="选择结束时间"
                  @change="checkTime"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="优惠形式" label-width="100px">
                <el-select
                  v-model="preferentialType"
                  style="width:90%"
                  size="mini"
                  placeholder="请选择"
                >
                  <el-option value="" label="全部" />
                  <el-option
                    v-for="item of payType"
                    :key="item.typeId"
                    :value="item.typeId"
                    :label="item.typeName"
                    :disabled="item.status"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2" class="flexd">
              <el-button
                size="mini"
                round
                icon="el-icon-refresh"
                @click="reset"
              >
                重置
              </el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="14">
              <el-form-item label="结束策略时间" label-width="100px">
                <el-date-picker
                  v-model="endDiscountStart"
                  :picker-options="pickerOptions3"
                  :editable="false"
                  :style="tiemLen"
                  type="datetime"
                  size="mini"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss   "
                  placeholder="选择开始时间"
                  @change="checkStartTime1"
                />
                至
                <el-date-picker
                  v-model="endDiscountEnd"
                  :picker-options="pickerOptions4"
                  :editable="false"
                  :style="tiemLen"
                  type="datetime"
                  size="mini"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss   "
                  placeholder="选择结束时间"
                  @change="checkStartTime2"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="app-table">
        <el-table
          ref="mult"
          :data="list"
          highlight-current-row
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <!-- <el-table-column label="序号" width="50">
             @selection-change="handleSelectionChange">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column> -->
          <el-table-column
            type="selection"
            width="55"
          >
            <!-- :selectable="selectInit" -->
          </el-table-column>
          <el-table-column label="策略名称">
            <template slot-scope="scope">
              <el-popover v-if="scope.row.name" :content="scope.row.name" placement="top" trigger="hover">
                <span slot="reference" style="cursor:pointer">{{ scope.row.name }}</span>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="策略开始时间">
            <template slot-scope="scope">
              <el-popover v-if="scope.row.beginTime" :content="scope.row.beginTime" placement="top" trigger="hover">
                <span slot="reference" style="cursor:pointer">{{ scope.row.beginTime }}</span>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="策略结束时间">
            <template slot-scope="scope">
              <el-popover v-if="scope.row.endTime" :content="scope.row.endTime" placement="top" trigger="hover">
                <span slot="reference" style="cursor:pointer">{{ scope.row.endTime }}</span>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="策略触发条件">
            <template slot-scope="scope">
              <el-popover v-if="scope.row.triggeringConditions" :content="scope.row.triggeringConditions" placement="top" trigger="hover">
                <span slot="reference" style="cursor:pointer">{{ scope.row.triggeringConditions }}</span>
              </el-popover>
            </template>
          </el-table-column>
          <!-- <el-table-column label="条件详情">
            <template slot-scope="scope">
              <el-popover v-if="scope.row.triggerConditionDetails" :content="scope.row.triggerConditionDetails" placement="top" trigger="hover">
                <span slot="reference" style="cursor:pointer">{{ scope.row.triggerConditionDetails }}</span>
              </el-popover>
            </template>
          </el-table-column> -->
          <el-table-column label="优惠形式">
            <template slot-scope="scope">
              <el-popover v-if="scope.row.preferentialType" :content="scope.row.preferentialType" placement="top" trigger="hover">
                <span slot="reference" style="cursor:pointer">{{ scope.row.preferentialType }}</span>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="优惠详情">
            <template slot-scope="scope">
              <div v-if="scope.row.preferentialType === '折扣购买'">
                <el-popover v-if="scope.row. discountRatio" :content="scope.row. discountRatio" placement="top" trigger="hover">
                  <span slot="reference" style="cursor:pointer">{{ scope.row. discountRatio }}</span>
                </el-popover>
              </div>

              <div v-else>
                <el-popover v-if="scope.row.discountAmount" :content="scope.row.discountAmount" placement="top" trigger="hover">
                  <span slot="reference" style="cursor:pointer">{{ scope.row.discountAmount }}</span>
                </el-popover>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination :current-page="pageid" :page-sizes="[20,50,100]" :page-size="pagecount" :total="count" background highlight-current-row layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <div class="btnArrs">
          <el-button
            type="primary"
            size="small"
            plain
            round
            @click="check"
          >取消</el-button>
          <el-button
            type="primary"
            size="small"
            round
            @click="connectList"
          >确认关联</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { discount, getSelectS } from '@/api/product.js'
export default {
  props: {
    addPlana: {
      type: Boolean,
      default: false
    },
    reIal: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      showPointDialog: false,
      endDiscountStart: '',
      startDiscount: '',
      tiemLen: '',
      startEndDiscount: '',
      endDiscountEnd: '',
      isGoon: '',
      preferentialType: '',
      serviceId: '',
      offlineStartTime: '',
      offlineEndTime: '',
      triggeringConditions: '',
      payType: '',
      triggeringConditionsArr: [],
      payCode: '', // 策略吗
      arr: [], // 多选
      list: [], // 请求列表
      name: '', // 策略名称
      flag: true,
      price: '', // 价格
      cycle: '', // 计费周期
      pay: [], // 支付渠道下拉
      connect: '', // 关联节目下拉
      associatedProgram: '', // 是否关联产品
      pageid: 1, // 当前页数
      pagecount: 20, // 每页可显示条数
      status: false, // 请求状态
      watchDialog: false, // 查看遮罩
      editDialog: false, // 编辑遮罩
      watchId: 0, // 策略id
      count: 0, // 总数量
      addDialog: false, // 新增遮罩
      paySelect: [],
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      pickerOptions2: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      pickerOptions3: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      pickerOptions4: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      pickerOptions5: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      pickerOptions6: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      }
    }
  },
  watch: {
    addPlana(newVal) {
      if (newVal) {
        console.log(this.reIal)
        this.$nextTick(() => {
          var len = this.$refs.vipHeight.$el.offsetWidth / 2 - 10
          console.log(len)
          this.tiemLen = {
            'width': len + 'px'
          }
        })
        this.showPointDialog = newVal
        this.loadList()
        this.getSelect()
      }
    }
  },
  methods: {
    selectInit(row, index) {
      console.log(row)
      console.log(index)
      /* if (this.arrMiddle.length > 0) {
        var arr = this.arrMiddle.map(item => {
          return item.serviceId
        })
        if (arr.indexOf(row.serviceId) > -1) {
          return false
        } else {
          return true
        }
      } else {
        return true
      } */
    },
    getSelect() {
      var data = {
        functionType: 'preferentialType'
      }
      getSelectS(data).then(res => {
        var list = res.data.list
        for (let i = 0; i < list.length; i++) {
          var key = list[i].typeId
          if (key !== '0' && key !== '1') {
            list[i].status = true
          }
        }
        this.payType = list
      })

      var data1 = {
        functionType: 'triggeringConditions'
      }
      getSelectS(data1).then(res => {
        var list = res.data.list
        for (let i = 0; i < list.length; i++) {
          var key = list[i].typeId
          if (key !== '0' && key !== '1') {
            list[i].status = true
          }
        }
        this.triggeringConditionsArr = list
      })
    },
    connectList() {
      if (Array.isArray(this.arr) && this.arr.length === 0) {
        this.$message({
          message: '请勾选优惠策略',
          type: 'error'
        })
        return false
      }
      if (Object.keys(this.arr).length > 0) {
        this.check(this.arr)
      } else {
        this.$message({
          message: '请勾选优惠策略',
          type: 'error'
        })
        return false
      }
    },
    // 多选变单选
    handleSelectionChange(val) {
      /* if (val && val.id) {
        this.arr = val
        this.list.forEach(item => {
          if (item.id !== val.id) {
            item.checked = false
          }
        })
      } */
      /* if (val.length === 1) {
        this.arr = val
      } */
      if (val.length > 1) {
        /* this.$message({
          type: 'error',
          message: '优惠策略只能勾选一条'
        }) */
        // this.$refs.mult.clearSelection()
        this.$refs.mult.toggleRowSelection(val[0], false)
        val.shift()
      }
      this.arr = val[0]
      console.log(val[0])
    },
    check(val) {
      this.showPointDialog = false
      this.$emit('closeDis', val)
      this.list.forEach(item => {
        item.checked = false
      })
    },

    // 请求列表
    loadList() {
      this.pageid = 1
      const request = {
        name: this.name, // 名称
        triggeringConditions: this.triggeringConditions, // 策略触发条件
        beginStartTime: this.startDiscount, // 策略开始开始时间
        beginEndTime: this.startEndDiscount, // 策略开始结束时间
        finishStartTime: this.endDiscountStart, // 策略结束开始时间
        finishEndTime: this.endDiscountEnd, // 策略结束开始时间
        preferentialType: this.preferentialType, // 优惠形式
        pageid: 1, // 当前页数
        pagecount: 20 // 每页可显示条数 */
      }
      discount(request).then(res => {
        if (res.resultCode === '0000') {
          this.list = res.data.list
          this.count = parseInt(res.data.count) // 总数量
          if (this.list.length > 0) {
            this.list.forEach(item => {
              item.checked = false
            })
            // this.pageid = parseInt(res.data.list[0].pageid) // 当前页数
          }
          this.status = true
          /* this.$nextTick(() => {
            this.toggleSelection()
          }) */
        }
      }).catch(() => {
        this.$message({
          message: '请求列表失败',
          type: 'error'
        })
      })
    },

    reset() {
      this.name = ''
      this.triggeringConditions = ''
      this.beginStartTime = ''
      this.beginEndTime = ''
      this.finishStartTime = ''
      this.finishEndTime = ''
      this.preferentialType = ''
    },
    // 请求支付渠道下拉
    /* getSelect() {
      var data = {
        functionType: 'productType'
      }
      getSelectS(data).then(res => {
        this.pay = res.data.list
      })
    }, */

    // 当前页面显示条数改变时
    handleSizeChange(num) {
      this.flag = false
      const request = {
        name: this.name, // 名称
        triggeringConditions: this.triggeringConditions, // 策略触发条件
        beginStartTime: this.startDiscount, // 策略开始开始时间
        beginEndTime: this.startEndDiscount, // 策略开始结束时间
        finishStartTime: this.endDiscountStart, // 策略结束开始时间
        finishEndTime: this.endDiscountEnd, // 策略结束开始时间
        preferentialType: this.preferentialType, // 优惠形式
        pageid: 1, // 当前页数
        pagecount: num // 每页可显示条数
      }
      console.log('请求数据')
      console.log(request)
      discount(request).then(res => {
        this.list = res.data.list // 列表项
        this.count = parseInt(res.data.count) // 总数量
        this.pageid = 1
        this.pagecount = num
        this.flag = true
      }).catch(() => {
        this.$message({
          message: '请求列表失败，请重试',
          type: 'error'
        })
      })
    },

    // 跳转某页
    handleCurrentChange(num) {
      console.log(num)
      this.pageid = num // 当前页数
      const request = {
        name: this.name, // 名称
        triggeringConditions: this.triggeringConditions, // 策略触发条件
        beginStartTime: this.startDiscount, // 策略开始开始时间
        beginEndTime: this.startEndDiscount, // 策略开始结束时间
        finishStartTime: this.endDiscountStart, // 策略结束开始时间
        finishEndTime: this.endDiscountEnd, // 策略结束开始时间
        preferentialType: this.preferentialType, // 优惠形式
        pageid: num, // 当前页数
        pagecount: this.pagecount // 每页可显示条数
      }
      console.log('请求数据')
      console.log(request)
      // if (this.flag === true) {
      discount(request).then(response => {
        this.list = response.data.list // 列表项
        this.count = parseInt(response.data.count) // 总数量
        console.log('返回数据')
        console.log(response.data)
      })
      // }
    },
    // 校验开始时间
    checkStartTime(time) {
      const reg = new RegExp('-', 'g')
      // 比较是否大于现在的时间
      var selectTime
      if (!!time) { // eslint-disable-line
        selectTime = new Date(time.replace(reg, '/')).getTime() // 所选时间
      } else {
        selectTime = ''
      }
      const nowTime = Date.now() // 现在的时间
      if (selectTime > nowTime) {
        this.$alert('所选时间不能大于当前时间！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.startDiscount = ''
          }
        })
      } else {
        if (!!time) {  // eslint-disable-line
          var end
          if (this.applyEndTime !== null) {
            end = new Date(this.startEndDiscount.replace(reg, '/')).getTime()
          } else {
            end = ''
          }
          var first = new Date(time.replace(reg, '/')).getTime()
          if (!!end && first > end) {
            this.$message({
              message: '开始时间不能大于结束时间',
              type: 'error'
            })
            this.startDiscount = ''
          }
        }
      }
    },
    // 校验开始时间
    checkStartTime1(time) {
      const reg = new RegExp('-', 'g')
      // 比较是否大于现在的时间
      var selectTime
      if (!!time) { // eslint-disable-line
        selectTime = new Date(time.replace(reg, '/')).getTime() // 所选时间
      } else {
        selectTime = ''
      }
      const nowTime = Date.now() // 现在的时间
      if (selectTime > nowTime) {
        this.$alert('所选时间不能大于当前时间！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.endDiscountStart = ''
          }
        })
      } else {
        if (!!time) {  // eslint-disable-line
          var end
          if (this.endDiscountEnd !== null) {
            end = new Date(this.endDiscountEnd.replace(reg, '/')).getTime()
          } else {
            end = ''
          }
          var first = new Date(time.replace(reg, '/')).getTime()
          if (!!end && first > end) {
            this.$message({
              message: '开始时间不能大于结束时间',
              type: 'error'
            })
            this.endDiscountStart = ''
          }
        }
      }
    },
    // 校验结束时间1
    checkStartTime2(time) {
      const reg = new RegExp('-', 'g')
      // console.log(newStr)
      var selectTime
      if (!!time) { // eslint-disable-line
        selectTime = new Date(time.replace(reg, '/')).getTime() // 所选时间
      } else {
        selectTime = ''
      }
      const nowTime = Date.now() // 现在的时间
      if (selectTime > nowTime) {
        this.$alert('所选时间不能大于当前时间！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.endDiscountEnd = ''
          }
        })
      } else {
        if (!!time) {  // eslint-disable-line
          var start
          if (this.endDiscountStart !== null) {
            start = new Date(this.endDiscountStart.replace(reg, '/')).getTime()
          } else {
            start = ''
          }
          var end = new Date(time.replace(reg, '/')).getTime()
          if (end < start) {
            this.$message({
              message: '开始时间不能大于结束时间',
              type: 'error'
            })
            this.endDiscountEnd = ''
          }
        }
      }
    },
    // 校验开始时间
    checkStartTime3(time) {
      const reg = new RegExp('-', 'g')
      // 比较是否大于现在的时间
      var selectTime
      if (!!time) { // eslint-disable-line
        selectTime = new Date(time.replace(reg, '/')).getTime() // 所选时间
      } else {
        selectTime = ''
      }
      const nowTime = Date.now() // 现在的时间
      if (selectTime > nowTime) {
        this.$alert('所选时间不能大于当前时间！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.offlineStartTime = ''
          }
        })
      } else {
        if (!!time) {  // eslint-disable-line
          var end
          if (this.offlineEndTime !== null) {
            end = new Date(this.offlineEndTime.replace(reg, '/')).getTime()
          } else {
            end = ''
          }
          var first = new Date(time.replace(reg, '/')).getTime()
          if (!!end && first > end) {
            this.$message({
              message: '开始时间不能大于结束时间',
              type: 'error'
            })
            this.offlineStartTime = ''
          }
        }
      }
    },
    // 校验开始时间
    checkStartTime4(time) {
      const reg = new RegExp('-', 'g')
      // 比较是否大于现在的时间
      var selectTime
      if (!!time) { // eslint-disable-line
        selectTime = new Date(time.replace(reg, '/')).getTime() // 所选时间
      } else {
        selectTime = ''
      }
      const nowTime = Date.now() // 现在的时间
      if (selectTime > nowTime) {
        this.$alert('所选时间不能大于当前时间！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.startDate = ''
          }
        })
      } else {
        if (!!time) {  // eslint-disable-line
          var end
          if (this.endDate !== null) {
            end = new Date(this.endDate.replace(reg, '/')).getTime()
          } else {
            end = ''
          }
          var first = new Date(time.replace(reg, '/')).getTime()
          if (!!end && first > end) {
            this.$message({
              message: '开始时间不能大于结束时间',
              type: 'error'
            })
            this.startDate = ''
          }
        }
      }
    },
    // 校验开始时间
    checkStartTime5(time) {
      const reg = new RegExp('-', 'g')
      // 比较是否大于现在的时间
      var selectTime
      if (!!time) { // eslint-disable-line
        selectTime = new Date(time.replace(reg, '/')).getTime() // 所选时间
      } else {
        selectTime = ''
      }
      const nowTime = Date.now() // 现在的时间
      if (selectTime > nowTime) {
        this.$alert('所选时间不能大于当前时间！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.startDate = ''
          }
        })
      } else {
        if (!!time) {  // eslint-disable-line
          var end
          if (this.endDate !== null) {
            end = new Date(this.endDate.replace(reg, '/')).getTime()
          } else {
            end = ''
          }
          var first = new Date(time.replace(reg, '/')).getTime()
          if (!!end && first > end) {
            this.$message({
              message: '开始时间不能大于结束时间',
              type: 'error'
            })
            this.startDate = ''
          }
        }
      }
    },
    // 校验结束时间
    checkTime(time) {
      const reg = new RegExp('-', 'g')
      // console.log(newStr)
      var selectTime
      if (!!time) { // eslint-disable-line
        selectTime = new Date(time.replace(reg, '/')).getTime() // 所选时间
      } else {
        selectTime = ''
      }
      const nowTime = Date.now() // 现在的时间
      if (selectTime > nowTime) {
        this.$alert('所选时间不能大于当前时间！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.startEndDiscount = ''
          }
        })
      } else {
        if (!!time) {  // eslint-disable-line
          var start
          if (this.startDiscount !== null) {
            start = new Date(this.startDiscount.replace(reg, '/')).getTime()
          } else {
            start = ''
          }
          var end = new Date(time.replace(reg, '/')).getTime()
          if (end < start) {
            this.$message({
              message: '开始时间不能大于结束时间',
              type: 'error'
            })
            this.startEndDiscount = ''
          }
        }
      }
    }
  }
}
</script>

<style scoped>
.addBtns{
  margin: 5px 0;
}
.btnArrs{
  display: flex;
  justify-content: flex-end;
  width: 200px;
  position: absolute;
  right: 0;
  bottom: -58px;
}
.app-table{
  position: relative;
}
.timeLength{
  width: 37.5% !important;
}
</style>
